package net.avcompris.binding.dom.testutil;

import static org.apache.commons.lang3.CharEncoding.UTF_8;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.avcompris.common.annotation.Nullable;
import com.avcompris.util.AbstractUtils;

/**
 * utility methods for tests on avc-binding-dom.
 */
public class LoadXmlUtils extends AbstractUtils {

	public static Node loadXml(final File file) throws ParserConfigurationException, SAXException, IOException {

		if (file==null || !file.exists()) {
			
			throw new IllegalArgumentException("File does not exist: "+file);
		}
		
		return loadXml(file, null);
	}

	/**
	 * load a DOM (= XML) document into a {@link Node} object.
	 * 
	 *   @param s the DOM document: May be a local filename, or an XML content.
	 */
	public static Node loadXml(final String s) throws ParserConfigurationException, SAXException, IOException {

		final File file = new File(s);

		final String xmlContent;

		if (file.exists()) {

			xmlContent = null;

		} else {

			xmlContent = s;
		}

		return loadXml(file, xmlContent);
	}

	private static Node loadXml(@Nullable final File file,
			@Nullable final String xmlContent) throws ParserConfigurationException, SAXException, IOException {

		final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();

		documentBuilderFactory.setNamespaceAware(true);

		final DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();

		assertTrue(documentBuilder.isNamespaceAware());

		final Document document;

		if (xmlContent == null) {

			document = documentBuilder.parse(file);

		} else {

			final InputStream is = new ByteArrayInputStream(xmlContent
					.getBytes(UTF_8));
			try {

				document = documentBuilder.parse(is);

			} finally {
				is.close();
			}
		}

		return document.getDocumentElement();
	}
}
